<template>
  <Card>
    <div :id="editorId"></div>
  </Card>
</template>

<script>
import Editor from 'wangeditor'
import axios from 'axios'
import 'wangeditor/release/wangEditor.min.css'
import { oneOf } from '@/libs/tools'

export default {
  name: 'Editor',
  props: {
    value: {
      type: String,
      default: ''
    },
    /**
     * 绑定的值的类型, enum: ['html', 'text']
     */
    valueType: {
      type: String,
      default: 'html',
      validator: (val) => {
        return oneOf(val, ['html', 'text'])
      }
    },
    /**
     * @description 设置change事件触发时间间隔
     */
    changeInterval: {
      type: Number,
      default: 200
    },
    /**
     * @description 是否开启本地存储
     */
    cache: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    editorId () {
      return `editor${this._uid}`
    }
  },
  methods: {
    setHtml (val) {
      this.editor.txt.html(val)
    },
    uploadToQiniu (file) {
      return new Promise(resolve => {
        // 创建form对象
        let param = new FormData()
        // 通过append向form对象添加数据
        param.append('file', file, file.name)
        param.append('token', 'l_Qy04YaEejPEbHcRoptsW1m2c1kzT9G51cAET95:oOtBlfJwmDR86DX5jfO9K6MzVs8=:eyJzY29wZSI6ImJhamlhb3dlYiIsImRlYWRsaW5lIjoxODY3Mzg4NDE3fQ==')
        // 添加请求头
        let config = {
          headers: { 'Content-Type': 'multipart/form-data' }
        }
        axios.post('http://upload.qiniu.com/', param, config)
          .then(response => {
            resolve(`http://img.bajiaostar.com/${response.data.key}`)
          })
      })
    }
  },
  mounted () {
    this.editor = new Editor(`#${this.editorId}`)
    this.editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024
    this.editor.customConfig.uploadImgMaxLength = 4
    this.editor.customConfig.uploadFileName = 'file'
    this.editor.customConfig.customUploadImg = (file, insertLinkImg) => {
      file.forEach(item => {
        this.uploadToQiniu(item).then(data => {
          insertLinkImg(data)
        })
      })
    }
    this.editor.customConfig.onchange = (html) => {
      // let text = this.editor.txt.text()
      if (this.cache) localStorage.editorCache = html
      this.$emit('update:value', html)
    }
    this.editor.customConfig.onchangeTimeout = this.changeInterval
    // create这个方法一定要在所有配置项之后调用
    this.editor.create()
    // 如果本地有存储加载本地存储内容
    setTimeout(() => {
      this.value && this.editor.txt.html(this.value)
    }, 1000)
  }
}
</script>

<style lang="less">
/*.editor-wrapper *{*/
  /*z-index: 100 !important;*/
/*}*/
</style>
